<!--
 * @Author: 哈尔滨大拐 3181845089@qq.com
 * @Date: 2022-07-10 17:41:16
 * @LastEditors: 哈尔滨大拐 3181845089@qq.com
 * @LastEditTime: 2022-08-02 20:50:54
 * @FilePath: \mygit\实验\18-淡入淡出.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="fade-obj" style="width:300px;height:300px;background:#000;opacity:1;"></div>
    <button id="fade-btn">淡出</button>
    <script>
        const fadeBtn = document.getElementById("fade-btn")
        const fadeObj = document.getElementById("fade-obj");

        fadeBtn.state = 0// 0:淡出 1:淡入
        let timer

        fadeBtn.addEventListener("click", function () {
            fadeBtn.disabled = true
            if (fadeBtn.state === 0) {//处理淡出

                timer = setInterval(() => {
                    fadeObj.style.opacity -= 0.01
                    if (fadeObj.style.opacity <= 0) {
                        clearInterval(timer)
                        fadeBtn.disabled = false
                        fadeBtn.innerHTML = '淡入'
                        fadeBtn.state = 1
                    }
                }, 10);

            } else {//处理淡入
                timer = setInterval(() => {
                    fadeObj.style.opacity = parseFloat(fadeObj.style.opacity) + 0.01
                    if (fadeObj.style.opacity >= 1) {
                        clearInterval(timer)
                        fadeBtn.disabled = false
                        fadeBtn.innerHTML = '淡出'
                        fadeBtn.state = 0
                    }
                }, 10);
            }
        }, false);

    </script>
</body>

</html>